import {PageContainer} from '@ant-design/pro-components';
import {useModel} from '@umijs/max';
import {Button, Card, Drawer, List} from 'antd';
import React, {useState} from 'react';
import {AccountBookOutlined, AppstoreAddOutlined, UserOutlined} from "@ant-design/icons";
import {NavLink} from "react-router-dom";
import './Welcome.less';
import TextArea from "antd/es/input/TextArea";
const Welcome: React.FC = () => {
  const {initialState} = useModel('@@initialState');
  const [open, setOpen] = useState(false);

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  const [userInput, setUserInput] = useState('');
  const [responses, setResponses] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleSend = () => {
    if (!userInput) return;

    setLoading(true);
    const eventSource = new EventSource(`http://localhost:8080/user/ai/ask?question=${userInput}`);

    eventSource.onmessage = (event) => {
      setResponses((prevResponses) => [...prevResponses, event.data]);
    };

    eventSource.onerror = () => {
      eventSource.close();
      setLoading(false);
    };

    eventSource.onclose = () => {
      setLoading(false);
    };
  };



  return (
    <>
      <Button icon={<UserOutlined />} type="default" size={'large'} onClick={showDrawer} style={{
        position: 'absolute',
        top: '21px',
        right: '42px',
        color: 'black',
        zIndex: 1000,
        backgroundColor: '#529cf6',
      }}>
        个人中心
      </Button>
      <Drawer title="个人中心" placement="right" onClose={onClose} open={open}>
        <NavLink to='/user/baseInfo' className="menu-item" ><UserOutlined/> <div className='nav-left-desc'>基本信息</div></NavLink>
        <NavLink to='/' className="menu-item" ><AppstoreAddOutlined /> <div className='nav-left-desc'>我的应用</div></NavLink>
        <NavLink to='/' className="menu-item" ><AccountBookOutlined /><div className='nav-left-desc'>我的订单</div></NavLink>
      </Drawer>
      <PageContainer title={'首页'}>
        <Card title="AI Chat" style={{ width: '100%', margin: '20px auto' }}>
          <TextArea
            rows={4}
            value={userInput}
            onChange={(e) => setUserInput(e.target.value)}
            placeholder="Type your question here..."
          />
          <Button type="primary" onClick={handleSend} loading={loading} style={{ marginTop: 10 }}>
            Send
          </Button>
          <List
            dataSource={responses}
            renderItem={(response, index) => (
              <List.Item key={index}>
                <Card style={{ width: '100%' }}>{response}</Card>
              </List.Item>
            )}
            style={{ marginTop: 20 }}
          />
        </Card>
      </PageContainer>
    </>
  );
};

export default Welcome;
